package uk.co.cocking.getinline2.pipeline.io;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import uk.co.cocking.getinline2.io.helpers.RssRecordBuilder;
import uk.co.cocking.getinline2.pipeline.transformers.AbstractTransformer;
import uk.co.cocking.getinline2.record.Record;
import de.nava.informa.core.ChannelIF;
import de.nava.informa.core.ItemIF;
import de.nava.informa.core.ParseException;
import de.nava.informa.impl.basic.ChannelBuilder;
import de.nava.informa.parsers.FeedParser;

public class RssConverter extends AbstractTransformer<String, Record> {

	private ChannelIF channel;
	private static Logger log = Logger
			.getLogger("uk.co.cocking.getinline2.processor.RssConverter");

	@Override
	public List<Record> transform(String rss) {
		List<Record> records = new ArrayList<Record>();
		try {
			channel = FeedParser.parse(new ChannelBuilder(), new StringReader(
					rss));
			Set<ItemIF> items = channel.getItems();
			for (ItemIF item : items) {
				Record record = new RssRecordBuilder().withTitle(
						item.getTitle()).withLink(item.getLink().toString())
						.withDescription(item.getDescription()).withGuid(
								item.getGuid().getLocation()).build();
				records.add(record);
			}
		} catch (ParseException e) {
			log.warn("error parsing RSS", e);
		} catch (IOException e) {
			log.warn("error reading RSS", e);
		}
		return records;
	}

}
